from __future__ import with_statement
def start(args):
    
    from .json_rpc import JSONHandler
    rpc = JSONHandler()
    
    loader = args['loader']
    
    loader.register_component('rpc', rpc)
    
    loader.register_component('rpc.JSONHandler', JSONHandler)
    
    router = loader.get_component('server.WSGI_Server').get_router()

    router.add_reserved([
        '/rpc',
        '/tree/*',
    ])

    #set up basic routes
    @router.route('/rpc')
    def route(header, request, response_headers):
        response_headers['Content-Type'] = 'application/json'
        return rpc.handle_call(request)
        
    @router.route('/tree/*')
    def route(header, request, response_headers):
        path = header['PATH_INFO'][1:]
        import os
        path = os.path.abspath(path)
        if path.endswith('.js'):
            response_headers['Content-Type'] = 'application/x-javascript'
        elif path.endswith('.css'):
            response_headers['Content-Type'] = 'text/css'
        with open(path, 'rb') as f:
            ret = f.read()
        return ret
    
def stop(args):
    router = loader.get_component('wsgi_server.WSGI_Server').get_router()
    for route in ('/tree/*', '/xmlrpc', '/json_rpc', '/json_rpc11'):
        router.delete_route(route)
